<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录页面</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            background-color: #f0f0f0;
        }

        .login-box {
            width: 300px;
            padding: 20px;
            background-color: white;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        .login-header {
            text-align: center;
            margin-bottom: 20px;
        }

        .login-form {
            margin-bottom: 10px;
        }

        .login-form input {
            width: 100%;
            padding: 8px;
            margin-bottom: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .login-form button {
            width: 100%;
            padding: 8px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .login-form button:hover {
            background-color: #45a049;
        }

        .register-link {
            text-align: center;
            margin-top: 10px;
        }

        .register-link a {
            color: #4CAF50;
            text-decoration: none;
        }
    </style>
</head>
<body>
    <div class="login-box">
        <div class="login-header">
            <h1>用户登录</h1>
        </div>
        <form class="login-form" id="loginForm">
            <input type="text" id="username" placeholder="用户名" required>
            <input type="password" id="password" placeholder="密码" required>
            <button type="submit">登录</button>
        </form>
        <div class="register-link">
            <a href="#" onclick="showRegisterForm()">没有账户？注册</a>
        </div>
    </div>

    <script>
        async function handleLogin(event) {
            event.preventDefault();
            
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;

            try {
                const response = await fetch('users.json');
                const users = await response.json();
                
                const user = users.find(u => u.username === username && u.password === password);
                if (user) {
                    // 登录成功，跳转到主页
                    localStorage.setItem('currentUser', username);
                    window.location.href = 'index.html';
                } else {
                    alert('用户名或密码错误');
                }
            } catch (error) {
                console.error('读取用户数据失败:', error);
                alert('登录失败，请检查网络连接');
            }
        }

        async function registerUser() {
            const username = document.getElementById('regUsername').value;
            const password = document.getElementById('regPassword').value;

            if (!username || !password) {
                alert('请输入用户名和密码');
                return;
            }

            try {
                const response = await fetch('users.json');
                const users = await response.json();
                
                const existingUser = users.find(u => u.username === username);
                if (existingUser) {
                    alert('用户名已存在');
                    return;
                }

                // 生成用户ID
                const newUser = {
                    id: Date.now(),
                    username,
                    password
                };

                // 更新users.json
                const newUsers = [...users, newUser];
                const responseUpdate = await fetch('users.json', {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(newUsers)
                });

                if (responseUpdate.ok) {
                    alert('注册成功，请登录');
                    // 关闭注册表单，回到登录页面
                    window.location.href = 'login.html';
                } else {
                    alert('注册失败，请检查网络连接');
                }
            } catch (error) {
                console.error('注册失败:', error);
                alert('注册失败，请检查网络连接');
            }
        }

        function showRegisterForm() {
            const loginBox = document.querySelector('.login-box');
            const loginForm = document.querySelector('#loginForm');
            const registerForm = document.createElement('div');
            registerForm.innerHTML = `
                <h2>用户注册</h2>
                <form id="registerForm">
                    <input type="text" id="regUsername" placeholder="用户名" required>
                    <input type="password" id="regPassword" placeholder="密码" required>
                    <button type="button" onclick="registerUser()">注册</button>
                </form>
                <button type="button" onclick="window.location.href='login.html'">返回登录</button>
            `;
            loginBox.replaceChild(registerForm, loginForm);
        }

        // 初始化登录表单提交事件监听
        document.getElementById('loginForm').addEventListener('submit', handleLogin);
    </script>
</body>
</html>